// 获取学生列表
async function getData(){
		
		const res  = await axios.get("/students")
		// console.log(res);
		document.querySelector('.username').innerText = localStorage.getItem('username')
		document.querySelector('.total').innerText = res.data.length
		// const {} = res.data
 		const dataHtml = res.data.map(v =>{
			const {name,age,gender,group,hope_salary,salary,province,city,area,id } = v
			return `
				<tr>
				  <td>${name}</td>
				  <td>${age}</td>
				  <td>${gender === 0 ? "男" : "女"}</td>
				  <td>第${group}组</td>
				  <td>${hope_salary}</td>
				  <td>${salary}</td>
				  <td>${province+city+area}</td>
				  <td data-id = "${id}" class ='controls'>
				    <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
				    <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
				  </td>
				</tr>
			`
		}).join("")
		document.querySelector('.list').innerHTML = dataHtml
		
}

getData()
exitLogin()

// 添加学员
const modalBox = document.querySelector('#modal')
const myModal = new bootstrap.Modal(modalBox)


const provinceDom = document.querySelector('[name = "province"]')
const cityDom = document.querySelector('[name = "city"]')
const areaDom = document.querySelector('[name = "area"]')

document.querySelector("#openModal").addEventListener('click', async function () {
	document.querySelector(".modal-title").innerText = '添加学员'
	document.querySelector("form").reset()
	// document.querySelector("#modal").classList.remove("data")
	delete document.querySelector("#modal").dataset.id
	cityDom.innerHTML = '<option value="">--城市--</option>' 
	areaDom.innerHTML = '<option value="">--地区--</option>' 
	myModal.show()
	// 获取省份
	try{
		const provinceData = await axios.get("/api/province")
		// console.log(provinceData);
		provinceDom.innerHTML = '<option value="">--省份--</option>'+provinceData.list.map( v =>{
			return `
			<option value="${v}">${v}</option>
			`
		}).join("")
		
	}catch(e){
		//TODO handle the exception
		// console.dir(e)
		// showToast(e.response)
	}	
})
// 获取市区
provinceDom.addEventListener("change", async function(){
	try{
		const cityData = await axios.get("/api/city",{
			params:{
				pname:provinceDom.value
			}
		})
		cityDom.innerHTML = '<option value="">--城市--</option>' + cityData.list.map(v =>{
			return `
			<option value="${v}">${v}</option>
			`
		}).join("")
		areaDom.innerHTML = '<option value="">--地区--</option>'
	}catch(e){
		//TODO handle the exception
	}
})
// 获取区
cityDom.addEventListener('change', async function(){
	try{
		const areaData = await axios.get("/api/area",{
			params:{
				pname:provinceDom.value,
				cname:cityDom.value
			}
		})
		areaDom.innerHTML = '<option value="">--地区--</option>' + areaData.list.map(v =>{
			return `
			<option value="${v}">${v}</option>
			`
		}).join("")
	}catch(e){
		//TODO handle the exception
	}
})

// 添加学员和更新学员（弹出框）
document.querySelector('#submit').addEventListener('click',async function(){
	// const modalBox = document.querySelector('#modal')
	// const myModal = new bootstrap.Modal(modalBox)
	const fromData = serialize(document.querySelector('#form'), { hash: true, empty: true })

	fromData.age = +fromData.age
	fromData.gender = +fromData.gender
	fromData.hope_salary = +fromData.hope_salary
	fromData.salary = +fromData.salary
	fromData.group = +fromData.group

	if (document.querySelector("#modal").dataset.id) {
			// console.log(111);
		try {
			const res = await axios.put(`/students/${document.querySelector("#modal").dataset.id}`, {...fromData})

			showToast(res.message)
			getData()
			
		} catch (error) {
			showToast(error.response.data.message)
		}
		myModal.hide()
			
	} else {

		try {
			const res = await axios.post("/students", { ...fromData })
			// console.log(res)
			// document.querySelector('.btn-secondary').click()
			showToast(res.message)
			getData()

		} catch (e) {
			//TODO handle the exception
			// console.dir(e)
			showToast(e.response.data.message)
		}
		myModal.hide()

	}
	
})

// 删除学员和更新学员
document.querySelector(".list").addEventListener("click", async function (e) {
	// console.log(e.target);
	
	if (e.target.classList.contains('bi-trash')) {
		// console.log(e);
		const id = e.target.parentNode.parentNode.dataset.id
		// console.log(id);

		try {
			const res = await axios.delete(`/students/${id}`)
			showToast('删除成功')
			getData()
		} catch (error) {
			
		}
		
	} else if (e.target.classList.contains("bi-pen")) {
		// console.log('111');
		const id = e.target.parentNode.parentNode.dataset.id
		// console.log(id);
		document.querySelector(".modal-title").innerText = '编辑学员'
		document.querySelector("#modal").dataset.id = id

		// 获取信息并展示到弹出框中
		const res = await axios.get(`/students/${id}`)
		// console.log(res);
		// console.log(Object.keys(res.data));
		
		const fromDom = serialize(document.querySelector("form"),{hash:true,empty:true})

		Object.keys(fromDom).forEach((key) => {
			document.querySelector(`[name = ${key}]`).value = res.data[key]
		})
		
		const provinceData = await axios.get("/api/province")
		provinceDom.innerHTML = '<option value="">--省份--</option>' + provinceData.list.map(v => {
			return `
			<option value="${v}">${v}</option>
			`
		}).join("")
		provinceDom.value = res.data['province']

		const cityData = await axios.get("/api/city",{params:{pname : res.data['province']}})
		cityDom.innerHTML = '<option value="">--城市--</option>' + cityData.list.map(v => {
			return `
			<option value="${v}">${v}</option>
			`
		}).join("")
		cityDom.value = res.data['city']

		const areaData = await axios.get("/api/area", { params: { pname: res.data['province'], cname: res.data['city']} })
		areaDom.innerHTML = '<option value="">--城市--</option>' + areaData.list.map(v => {
			return `
			<option value="${v}">${v}</option>
			`
		}).join("")
		areaDom.value = res.data['area']

		myModal.show()

		
	}
})